package com.briup.product_source.config;

import com.briup.product_source.web.interceptor.LoggerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    //添加拦截器

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //通过注册器registry,把指定拦截器添加到springboot中
        System.out.println("注册拦截器");
        registry.addInterceptor(new LoggerInterceptor())
                .addPathPatterns("/**")//拦截所有的请求路径
                .excludePathPatterns("/animal/findByAnimalId",
                                     "/swagger-resources/**",
                                     "/webjars/**",
                                     "/v2/api-docs/**",
                                     "/swagger-ui.html",
                                     "/error","/csrf","/");//排除swagger请求路径，不进行拦截
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //解决跨域的访问：规则：当浏览器跨域发送任意url 请求方式任意，请求头任意的请求都可以访问后端资源
        // 设置允许跨域的路径
        registry.addMapping("/**")
                  // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                  // 是否允许cookie
                .allowCredentials(true)
                 // 设置允许的请求方式
                .allowedMethods("GET", "POST", "DELETE",
                        "PUT","HEAD","OPTIONS")
                // 设置允许的header属性
                .allowedHeaders("*")
                 // 跨域允许时间
                .maxAge(3600);
    }
}
